package com.kgc.springboot.hangduo.controller;

import com.kgc.springboot.hangduo.pojo.Laws;
import com.kgc.springboot.hangduo.service.LawsService;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;

/**
 * @author: ASUS
 * @date: 2020/12/26 20:35
 * @description:
 */
@Controller
public class LawsController {
    @Autowired
    LawsService lawsService;
    @RequestMapping("/law-list.html")
    public String selectAll(Model model){
        List<Laws> laws = lawsService.selectAll();
        model.addAttribute("lawsList",laws);
        return "law-list";
    }

    @RequestMapping("selectLaws")
    public String selectLaws(
            @RequestParam(value = "alias", required = false) String alias,
            @RequestParam(value = "title", required = false) String title,
            Model model
    ) {
        List<Laws> list = lawsService.selectLaws(alias, title);
        model.addAttribute("lawsList", list);
        model.addAttribute("alias", alias);
        model.addAttribute("title", title);
        return "law-list";
    }
    @RequestMapping("addLaws")
    @ResponseBody
    public String addLaws(Model model, Laws laws, @RequestParam("lawsFile") MultipartFile lawsFile, HttpServletRequest request) {
        int i = -1;
        if(lawsFile!=null){
            String path = "E:/idea-workspace/hangduo/src/main/resources/static/lawFiles/";
            String oldFileName = lawsFile.getOriginalFilename();
            //获取扩展名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            //生成新文件名
            String fileName = laws.getLawsAlias() + "." + prefix;
            //封装文件对象
            File targetFile = new File(path, fileName);
            try {
                //实现上传
                lawsFile.transferTo(targetFile);
                laws.setLawsPath(fileName);
                i = lawsService.addLaws(laws);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            i = lawsService.addLaws(laws);
        }
        if (i>0){
            return "<script language='javascript'>" +
                    "var index = parent.layer.getFrameIndex(window.name);\n" +
                    "parent.layer.close(index);" +
                    "window.location.href='/selectLaws';" +
                    "alert('添加成功');" +
                    "</script>";
        }else{
            return "<script language='javascript'>" +
                    "var index = parent.layer.getFrameIndex(window.name);\n" +
                    "parent.layer.close(index);" +
                    "window.location='/selectLaws';" +
                    "alert('添加失败');" +
                    "</script>";
        }
    }

    @RequestMapping("deleteLaw")
    @ResponseBody
    public String deleteLaw(int id){
        int i = lawsService.deleteLaws(id);
        if (i>0){
            return "1";
        }else{
            return "0";
        }
    }

    @RequestMapping("toUpdateLaw")
    public String toUpdateLaw(int id,Model model){
        Laws laws = lawsService.selectLawsById(id);
        model.addAttribute("law", laws);
        return "law-update";
    };

    @RequestMapping("updateLaw")
    @ResponseBody
    public String updateLaw(Model model, Laws laws, @RequestParam(value = "lawsFile",required = false)MultipartFile lawsFile, HttpServletRequest request){
        int i = -1;
        if(lawsFile!=null){
            String path = "E:/idea-workspace/hangduo/src/main/resources/static/lawFiles/";
            String oldFileName = lawsFile.getOriginalFilename();
            //获取扩展名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            //生成新文件名
            String fileName = laws.getLawsAlias() + "." + prefix;
            //封装文件对象
            File targetFile = new File(path, fileName);
            try {
                //实现上传
                lawsFile.transferTo(targetFile);
                laws.setLawsPath(fileName);
                i = lawsService.updateLaws(laws);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            i = lawsService.updateLaws(laws);
        }
        if (i>0){
            return "<script language='javascript'>" +
                    "var index = parent.layer.getFrameIndex(window.name);\n" +
                    "parent.layer.close(index);" +
                    "window.location.href='/selectLaws';" +
                    "alert('修改成功');" +
                    "</script>";
        }else{
            return "<script language='javascript'>" +
                    "var index = parent.layer.getFrameIndex(window.name);\n" +
                    "parent.layer.close(index);" +
                    "window.location='/selectLaws';" +
                    "alert('修改失败');" +
                    "</script>";
        }

    }


    //********************************************前端功能**********************************************
    @RequestMapping("/selectAllLaws")
    public String selectAllLaws(Model model){
        List<Laws> laws = lawsService.selectAll();
        model.addAttribute("laws",laws);
        return "user-index";
    }

    @RequestMapping("toDownloadLaw")
    public String toDownloadLaw(Integer lid,Model model){
        Laws laws = lawsService.selectLawsById(lid);
        model.addAttribute("law",laws);
        return "law-download";


    }

    @ResponseBody
    @RequestMapping("downloadLaw")
    public void downloadLaw(String path, HttpServletResponse response){
        String realPath = "E:/idea-workspace/hangduo/src/main/resources/static/lawFiles/";
        // 封装的是服务器资源
        File file = new File(realPath, path);
        //设置响应类型  ==》 告诉浏览器当前是下载操作，我要下载东西
        response.setContentType("application/x-msdownload");
        //设置下载时文件的显示类型(即文件名称-后缀)   ex：txt为文本类型
        response.setHeader("Content-Disposition", "attachment;filename=" + path);
        //下载文件：将一个路径下的文件数据转到一个输出流中，也就是把服务器文件通过流写(复制)到浏览器端
        try {
            Files.copy(file.toPath(), response.getOutputStream());//Files.copy(要下载的文件的路径,响应的输出流)
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
